package kc.test.kmeans;

import java.awt.geom.Point2D;
import java.awt.Color;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


/**
 * @author Thomas Neidhart, thomas.neidhart@gmail.com, all rights by Know-Center
 * Date: Aug 3, 2005
 *
 * Represents a cluster centroid
 */
public class Centroid extends Point
{
    private ArrayList<Point> points;
    private ArrayList<HPoint> history;
    
    public Centroid(Point p, Color c){
    	super(p.getP().getVec());
    	m_c = c;
        points = new ArrayList<Point>();
        history = new ArrayList<HPoint>();
    }
    /**
     * Create a new centroid object
     * @param p the point on the x-y plane
     * @param c the color associated with this cluster
     */
    public Centroid(Point2D p, Color c) {
        super(p, c);

        points = new ArrayList<Point>();
        history = new ArrayList<HPoint>();
    }

    /**
     * add a point to the point list
     * @param p
     */
    public void addPoint(Point p) {
        points.add(p);
    }

    /**
     * clear point list
     */
    public void clearPoints() {
        points.clear();
    }

    /**
     * get an iterator containing all points associated with this cluster centroid
     * @return
     */
    public List<Point> getPoints() {
        return points;
    }

    /**
     * add a 2d point as track for history information
     * @param p the point
     */
    public void addTrack(Point2D p) {
        history.add(new HPoint(p));
    }

    public void addTrack(HPoint p) {
        history.add(new HPoint(p.getVec()));
    }
    /**
     * Get a list of all history points
     * @return
     */
    public List<Point2D> getHistory() {
    	List<Point2D> his = new LinkedList<Point2D>();
    	for (HPoint hp : history){
    		his.add(new Point2D.Double(hp.getX(),hp.getY()));
    	}
        return his;
    }
    public List<HPoint> getHPointHistory(){
    	return history;
    }

    /**
     * Clear the history information
     */
    public void clearHistory() {
        history.clear();
    }

    /**
     * create a clone of this centroid
     * @return the clone centroid
     */
    public Centroid clone() {
        Centroid c = null;
        c = (Centroid) super.clone();
        return c;
    }
    
    public void updateToCenter(){
    	int num_points = getPoints().size();
    	double[] ds = new double[getP().getDimCnt()];
    	for (int i = 0; i < ds.length; i++) {
			ds[i] = 0;
		}
    	for(Point p : points){
    		double[] tmp = p.getP().getVec();
    		for (int i = 0; i < tmp.length; i++) {
				ds[i] += tmp[i];
			}
    	}
    	for (int i = 0; i < ds.length; i++) {
			ds[i] /= num_points;
		}
    	getP().setLocation(ds);
    }
}
